package com.r2coding.domain.strategy.service.rule.impl;

import com.r2coding.domain.strategy.model.entity.RuleActionEntity;
import com.r2coding.domain.strategy.model.entity.RuleMatterEntity;
import com.r2coding.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.r2coding.domain.strategy.repository.IStrategyRepository;
import com.r2coding.domain.strategy.service.rule.IRuleLogicFilter;
import com.r2coding.domain.strategy.service.rule.factory.DefaultLogicFactory;
import com.r2coding.types.common.Constants;
import com.r2coding.types.enums.ResponseCode;
import com.r2coding.types.exception.AppException;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

/**
 * @author caolx
 * @description 用户列表规则过滤器抽象基类（黑名单/白名单通用逻辑）
 * @date 2025/8/2 15:30
 */
@Slf4j
public abstract class AbstractUserListLogicFilter implements IRuleLogicFilter<RuleActionEntity.RaffleBeforeEntity> {

    @Resource
    protected IStrategyRepository strategyRepository;

    @Override
    public RuleActionEntity<RuleActionEntity.RaffleBeforeEntity> filter(RuleMatterEntity ruleMatterEntity) {
        log.info("规则过滤-{} userId: {}, strategyId: {}", getFilterType(),
                ruleMatterEntity.getUserId(), ruleMatterEntity.getStrategyId());

        String userId = ruleMatterEntity.getUserId();
        String ruleValue = strategyRepository.queryStrategyRuleValue(
                ruleMatterEntity.getStrategyId(),
                ruleMatterEntity.getAwardId(),
                ruleMatterEntity.getRuleModel());

        // 解析配置：100:user001,user002,user003（100是奖品ID）
        UserListConfig config = parseRuleValue(ruleValue);

        // 检查用户是否在列表中
        boolean isUserInList = isUserInList(userId, config.getUserList());

        if (isUserInList) {
            // 命中列表时的处理逻辑
            return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                    .ruleModel(getRuleModel().getCode())
                    .code(RuleLogicCheckTypeVO.TAKE_OVER.getCode())
                    .info(RuleLogicCheckTypeVO.TAKE_OVER.getInfo())
                    .data(RuleActionEntity.RaffleBeforeEntity.builder()
                            .strategyId(ruleMatterEntity.getStrategyId())
                            .awardId(config.getAwardId())
                            .build())
                    .build();
        }

        // 未命中时返回放行
        return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                .build();
    }

    /**
     * 解析规则配置
     */
    private UserListConfig parseRuleValue(String ruleValue) {
        String[] ruleValueGroup = ruleValue.split(Constants.COLON);
        if (ruleValueGroup.length != 2) {
            throw new AppException(getConfigErrorCode().getCode(), getConfigErrorCode().getInfo());
        }

        Integer awardId = Integer.valueOf(ruleValueGroup[0]);
        String[] userList = ruleValueGroup[1].split(Constants.SPLIT);

        return new UserListConfig(awardId, userList);
    }

    /**
     * 检查用户是否在列表中
     */
    private boolean isUserInList(String userId, String[] userList) {
        for (String listUserId : userList) {
            if (userId.equals(listUserId)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取过滤器类型描述（用于日志）
     */
    protected abstract String getFilterType();

    /**
     * 获取规则模型
     */
    protected abstract DefaultLogicFactory.LogicModel getRuleModel();

    /**
     * 获取配置错误码
     */
    protected abstract ResponseCode getConfigErrorCode();

    /**
     * 用户列表配置内部类
     */
    @Getter
    private static class UserListConfig {
        private final Integer awardId;
        private final String[] userList;

        public UserListConfig(Integer awardId, String[] userList) {
            this.awardId = awardId;
            this.userList = userList;
        }

    }
}